<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <el-dialog v-model="dialogVisible" title="零件清单" width="1200" :before-close="handleClose">
    <el-descriptions>
      <el-descriptions-item label="部段名称：">{{ datas.section }}</el-descriptions-item>
      <el-descriptions-item label="主部段：">{{ datas.mainSection }}</el-descriptions-item>
      <el-descriptions-item label="部段所在ATA：">{{ datas.ata }}</el-descriptions-item>
      <el-descriptions-item label="所属机型：">{{ datas.aircraftModel }}</el-descriptions-item>
      <el-descriptions-item label="所属批次：">{{ datas.track }}</el-descriptions-item>
      <el-descriptions-item label="数据产生日期：">{{ datas.createTime }}</el-descriptions-item>
      <el-descriptions-item label="数据来源：">{{ datas.srcDesc }}</el-descriptions-item>
      <el-descriptions-item label="变更原因：">{{ datas.summary }}</el-descriptions-item>
    </el-descriptions>
    <div class="title">数据清单</div>
    <el-form inline :model="dialogForm" class="p-t-2" size="small">
      <el-form-item prop="code" label="零组件编号" label-width="82px">
        <el-input v-model="dialogForm.code" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item prop="name" label="零件名称">
        <el-input v-model="dialogForm.name" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getList">查询</el-button>
      </el-form-item>
    </el-form>
    <div class="p-b-2">
      <el-button v-if="!dataEdit" type="primary" @click="handleDataEdit">数据修改</el-button>
      <el-button v-if="!dataEdit" type="primary" @click="exportData">数据导出</el-button>
      <el-button v-if="dataEdit" type="primary" @click="handleDeleteBatch">批量删除</el-button>
    </div>
    <el-table v-loading="loading" :data="tableDatas" row-key="id" @selection-change="handleSelectionChange">
      <el-table-column v-if="dataEdit" type="selection" reserve-selection></el-table-column>
      <el-table-column prop="code" label="零组件编号"></el-table-column>
      <el-table-column prop="name" label="零件名称"></el-table-column>
      <el-table-column prop="cnt" label="数量"></el-table-column>
      <el-table-column label="操作" fixed="right">
        <template #default="scope">
          <el-button type="text" @click="handleDelete(scope.row.id, scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" v-model:page="dialogForm.pageNum" v-model:limit="dialogForm.pageSize" :total="total" @pagination="getList" />
    <el-form v-if="dataEdit" ref="paramFormRef" :model="paramForm" class="p-t-5" :rules="rules">
      <el-form-item prop="desc" label="变更原因">
        <el-input v-model="paramForm.desc" placeholder="请输入变更原因" type="textarea" maxlength="200" :autosize="{ minRows: 2 }" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button v-if="!dataEdit" type="primary" @click="handleClose"> 关闭窗口</el-button>
        <el-button v-if="dataEdit" @click="handleClose">取消</el-button>
        <el-button v-if="dataEdit" type="primary" @click="handleSave"> 确认并保存为新记录</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="PartListDialog" lang="ts">
import { detailStandardList, exportStandard, updateStandard } from '@/api/bomCompareTool/standardInstallationList/index';
const { proxy } = getCurrentInstance();
const emit = defineEmits(['on-sure']);
const dialogVisible = ref(false);
const datas = reactive({
  id: '',
  section: '',
  mainSection: '',
  ata: '',
  aircraftModel: '',
  track: '',
  createTime: '',
  srcDesc: '',
  summary: ''
});
const dataEdit = ref(false);
const loading = ref(true);
const total = ref(0);
const multipleSelection = ref([]);
const ids = ref([]);
const paramFormRef = ref();
const dialogForm = reactive({
  code: '',
  name: '',
  aircraftModel: '',
  infoId: '',
  pageNum: 1,
  pageSize: 10
});
const paramForm = reactive({
  desc: ''
});
const rules = reactive({
  desc: [{ required: true, message: '请输入变更原因', trigger: 'blur' }]
});
const tableDatas = ref([]);
const getList = async () => {
  loading.value = true;
  const res = await detailStandardList(dialogForm).catch(() => {
    loading.value = false;
  });
  tableDatas.value = res.rows.filter((item) => !ids.value.includes(item.id));
  total.value = res.total;
  loading.value = false;
};
const handleClose = () => {
  dialogVisible.value = false;
};
const openDialog = async (obj) => {
  for (const key in datas) {
    datas[key] = obj[key];
  }
  dialogForm.aircraftModel = datas.aircraftModel;
  dialogForm.infoId = datas.id;
  paramForm.desc = '';
  getList();
  dialogVisible.value = true;
};
const handleDataEdit = () => {
  dataEdit.value = true;
};
const downloadFile = (res, fileName) => {
  const blob = new Blob([res]);
  const objUrl = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.setAttribute('href', objUrl);
  link.setAttribute('download', fileName);
  link.style.display = 'none';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
// 下载文件
const exportData = () => {
  const obj = {
    aircraftModel: datas.aircraftModel,
    id: datas.id
  };
  exportStandard(obj).then((res) => {
    const contentDisposition = res.headers['content-disposition'];
    if (contentDisposition) {
      // 使用正则表达式提取filename（注意：这里的正则需要根据实际Content-Disposition的格式进行调整）
      const filename = contentDisposition.match(/filename="?([^"]+)"?/)[1];
      const fileName = decodeURIComponent(filename);
      downloadFile(res.data, fileName);
    }
  });
};
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};
const handleDeleteBatch = async () => {
  if (!multipleSelection.value.length) {
    proxy?.$modal.msgWarning('请选择一条数据！');
    return false;
  }
  await proxy?.$modal.confirm('是否确认删除选择数据？');
  const idDatas = multipleSelection.value.map((item) => item.id);
  tableDatas.value = tableDatas.value.filter((item) => !idDatas.includes(item.id));
  ids.value = [...ids.value, ...idDatas];
};
const handleDelete = async (id, index) => {
  await proxy?.$modal.confirm('是否确认删除该数据？');
  tableDatas.value.splice(index, 1);
  ids.value.push(id);
};
const handleSave = async () => {
  await paramFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      const obj = {
        srcStandardBomId: datas.id,
        desc: paramForm.desc,
        deleteDetailIds: ids.value
      };
      updateStandard(obj).then((res) => {
        proxy?.$modal.msgSuccess('保存为新记录成功！');
        emit('on-sure');
        dialogVisible.value = false;
      });
    } else {
      proxy?.$modal.msgWarning('请填写完整信息！');
    }
  });
  console.log(ids.value);
};
defineExpose({
  openDialog
});
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: center;
}
</style>
